package com.ecole.mines.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.ecole.mines.model.Cours;
import com.ecole.mines.model.Promotion;

public class ParserJSON extends
		AsyncTask<String, Integer, ArrayList<Promotion>> {
	private OnTaskCompleted listener;
	private static final String URL_SERVEUR = "http://91.121.167.164/Emargement-Web/web/app_dev.php";

	// constructor
	public ParserJSON() {
	}

	public ParserJSON(OnTaskCompleted listener) {
		this.listener = listener;
	}

	@Override
	protected ArrayList<Promotion> doInBackground(String... params) {
		JSONArray jArray = getJSONFromUrl(params[0]);
		if (jArray != null && jArray.length() > 0) {
			return this.parserJSON(jArray);
		} else
			return new ArrayList<Promotion>();
	}

	@Override
	protected void onPostExecute(ArrayList<Promotion> result) {
		listener.onTaskCompletedPromo(result);
	}

	public JSONArray getJSONFromUrl(String url) {

		InputStream is = null;
		JSONArray jArr = null;
		String json = "";

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(URL_SERVEUR + url);
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse httpResponse = httpClient.execute(httpPost);

			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			//System.out.println("sb " + sb.toString());
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jArr = new JSONArray(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			jArr = null;
		}

		return jArr;
	}

	public ArrayList<Promotion> parserJSON(JSONArray jsonArray) {

		ArrayList<Promotion> promotions = new ArrayList<Promotion>();
		for (int i = 0; i < jsonArray.length(); i++) {
			Promotion p = new Promotion();
			JSONObject object = new JSONObject();
			JSONArray arrayCours = new JSONArray();
			try {
				object = (JSONObject) jsonArray.get(i);
				p.setName(object.optString("name"));
				p.setId(object.optInt("id"));
				p.setCours(new ArrayList<Cours>());

				JSONObject coursTemp = new JSONObject();
				arrayCours = object.getJSONArray("cours");
				for (int j = 0; j < arrayCours.length(); j++) {
					coursTemp = (JSONObject) arrayCours.get(j);
					Cours cours = new Cours();
					try {
						cours.setId(coursTemp.optInt("id_cours"));
						cours.setNom(coursTemp.optString("name"));
						cours.setProf(coursTemp.optString("prof"));
						cours.setSalle(coursTemp.optString("salle"));
						cours.setDate(new SimpleDateFormat("yyyyMMdd",
								Locale.FRANCE).parse(coursTemp
								.optString("date")));
						cours.setHeureDebut(new SimpleDateFormat("kkmm",
								Locale.FRANCE).parse(coursTemp.optString("hd")));
						cours.setHeureFin(new SimpleDateFormat("kkmm",
								Locale.FRANCE).parse(coursTemp.optString("hf")));
						cours.setGroupe(coursTemp.optString("id_groupe"));
					} catch (ParseException e) {
						Log.i("PARSER", e.getMessage());
					}
					p.getCours().add(cours);
				}
			} catch (JSONException e) {
				Log.e("PARSER", e.getMessage());
			}
			promotions.add(p);
		}

		return promotions;
	}
}
